<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="inside">0</div>
  <button id="start">开始</button>
  <button id="end">结束</button>
  <script>
    let inside = document.querySelector('#inside')
    let start = document.querySelector('#start')
    let end = document.querySelector('#end')
    let count = 0
    start.addEventListener('click', throttle(addCount, 1000))
    function addCount (e) {
      console.log(e.target, this);
      inside.innerHTML = ++count
      // return count
    }
    // function throttle (fn, wait) {
    //   let previous = 0
    //   return function () {
    //     let context = this
    //     let args = arguments
    //     let now = +(new Date())
    //     if (now - previous > wait) { // 第一次就会触发 wait时间内不会触发
    //       fn.apply(context, args)
    //       previous = now
    //     }
    //   }

    // }
    function throttle (fn, time) {
      let timer = null
      return function () {
        let context = this
        let args = [...arguments]
        if (!timer) {
          timer = setTimeout(() => {
            fn.apply(context, args)
            timer = null
          }, time);
        }
      }
    }
  // let timer = null
      // return function () {
      //   let context = this
      //   let args = arguments
      //   if (!timer) { // wait时间过后第一次触发
      //     timer = setTimeout(() => {
      //       fn.apply(context, args)
      //       timer = null
      //     }, wait);
      //   }
      // }
  </script>
</body>

</html>